package com.nifostasky.comic.common.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * url请求工具类
 */
public class URLUtils {

    /**
     * url: 请求地址
     * param： 请求参数 [{'key1':'value1','key2':'value2'},{'key1':'value3','key2':'value4'}]
     * header 设置header
     *
     */
    public static String sendPost(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException, IOException {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        //设置超时时间
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(15000);
        // 设置通用的请求属性
        if (header!=null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new PrintWriter(conn.getOutputStream());
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "utf8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        if(out!=null){
            out.close();
        }
        if(in!=null){
            in.close();
        }
        return result;
    }

    /**
     * HttpGet请求
     * @param vurl:请求地址,map:{头部信息}
     * @return 返回消息
     */
    public static String httpGet(String vurl, HashMap<String, Object> map) {
        try {
            URL url = new URL(vurl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            for (Map.Entry item : map.entrySet()) {
                connection.setRequestProperty(item.getKey().toString(),item.getValue().toString());//设置header
            }
            InputStream in = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(in, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            isr.close();
            in.close();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * HttpGet请求
     * @param vurl:请求地址,map:{头部信息}
     * @return 返回消息
     */
    public static InputStream httpInputGet(String vurl, Map<String, Object> map) {
        try {
            String encode = URLUtils.changeChineseUrl(vurl);
            URL url = new URL(encode);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            for (Map.Entry item : map.entrySet()) {
                connection.setRequestProperty(item.getKey().toString(),item.getValue().toString());//设置header
            }
            InputStream in = connection.getInputStream();
            return in;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 处理url中的汉字及空格
     */
    public static String changeChineseUrl(String url) throws UnsupportedEncodingException {
        StringBuilder resultURL = new StringBuilder();
        for (int i = 0; i < url.length(); i++) {
            char charAt = url.charAt(i);
            //只对汉字处理
            if (URLUtils.isChineseChar(charAt)) {
                String encode = URLEncoder.encode(charAt+"","UTF-8");
                resultURL.append(encode);
            }else {
                resultURL.append(charAt);
            }
        }
        return resultURL.toString();
    }

    /**
     *     判断汉字及空格的方法,只要编码在\u4e00到\u9fa5之间的都是汉字, \s表示空格
     *     空格 \s
     */
    public static boolean isChineseChar(char c) {
        return String.valueOf(c).matches("[\u4e00-\u9fa5\\s]");
    }
}
